<template>
  <div class="app-container">
    <audit-filter @on-filter="submitFilterForm"/>
    <div style="padding: 20px 0">
      <el-button-group>
        <el-button size="mini" type="primary" icon="el-icon-download" @click="exportHandle">导出
        </el-button>
      </el-button-group>
    </div>
    <el-table
      show-summary
      :summary-method="getSummaries"
      border
      :data="tableData.list" v-loading="loading" element-loading-text="加载中...">
      <el-table-column label="资金调整单号" prop="orderId" align="center" width="190">
      </el-table-column>
      <el-table-column label="账户类型" prop="userType" align="center">
        <template slot-scope="{row}">
          {{row.userType | toConverter('ACCOUNT_TYPE')}}
        </template>
      </el-table-column>
      <el-table-column label="账户名" prop="username" align="center">
      </el-table-column>
      <el-table-column label="调整类型" prop="changeType" align="center" width="120">
        <template slot-scope="{row}">
          {{row.changeType | toSwitchStr}}
        </template>
      </el-table-column>
      <el-table-column label="细分类型" prop="subType" align="center" width="120">
        <template slot-scope="{row}">
          {{row.subType | toSwitchStr}}
        </template>
      </el-table-column>
      <el-table-column label="调整金额" prop="amount" align="center" width="120">
        <template slot-scope="{row}">
          <span  v-if="row.changeType!=-2">{{row.amount | currency}}</span>
          <span v-else> {{-row.amount | currency}}</span>
        </template>
      </el-table-column>
      <el-table-column label="需求流水金额" prop="freezeAmount" align="center" width="120">
        <template slot-scope="{row}">
          <span> {{row.freezeAmount | currency}}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整原由" prop="remark" align="center" width="120"></el-table-column>
      <el-table-column label="申请人" prop="creator" align="center">
      </el-table-column>
      <el-table-column label="申请时间" prop="createTime" width="180" align="center">
        <template slot-scope="{row}">
          {{row.createTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="一审状态" prop="status" align="center">
        <template slot-scope="{row}">
          <el-button  type="text" v-if="row.status === 0 && roleCheck('first-audit')&&(row.subType===9?(row.changeType===1018?dataRoleCheck(dataPermissionObj[row.subType][0][0]):dataRoleCheck(dataPermissionObj[row.subType][1][0])):dataRoleCheck(dataPermissionObj[row.subType][0]))" @click="toAudit(row, 0)">待审核</el-button>
          <el-button type="text" v-else-if="row.status=== 1 || row.status>2 " @click="showAuditDialog(row,1)">审核通过
          </el-button>
          <el-button type="text" v-else-if="row.status=== 2" @click="showAuditDialog(row,1)">审核未通过</el-button>
        </template>
      </el-table-column>
      <el-table-column label="一审人" prop="firstApprover" align="center">
      </el-table-column>
      <el-table-column label="审核时间" prop="firstTime" align="center" width="180">
        <template slot-scope="{row}">
          {{row.firstTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="二审状态" prop="status" align="center">
        <template slot-scope="{row}" v-if="row.status === 1 || row.status>2">
          <el-button type="text" v-if="row.status === 1 &&  roleCheck('second-audit')&&(row.subType===9?(row.changeType===1018?dataRoleCheck(dataPermissionObj[row.subType][0][1]):dataRoleCheck(dataPermissionObj[row.subType][1][1])):dataRoleCheck(dataPermissionObj[row.subType][1]))" @click="toAudit(row, 1)">待审核</el-button>
          <el-button type="text" v-else-if="row.status=== 3" @click="showAuditDialog(row,2)">审核通过</el-button>
          <el-button type="text" v-else-if="row.status=== 4" @click="showAuditDialog(row,2)">审核未通过</el-button>
        </template>
      </el-table-column>
      <el-table-column label="二审人" prop="secondApprover" align="center">
      </el-table-column>
      <el-table-column label="审核时间" prop="secondTime" align="center" width="180">
        <template slot-scope="{row}">
          {{ row.secondTime | toTime}}
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>
    <audit-dialog
      v-model="auditDialogVisible"
      v-if="auditDialogVisible"
      :id="rowData.id"
      :row-data="rowData"
      :audit-step="auditStep"
      :menuId="menuId"
    />
  </div>
</template>


<script>
import { getAdjustmentList, exportAduitLogs } from '@/services/api/adjustment';
import AuditDialog from './auditDialog';
import { grid } from '@/build';
import AuditFilter from '@/views/finance/adjustment/auditFilter';
import dataPermission from '@/const/dataPermission';

export default {
  name: 'member-audit',
  components: { AuditFilter, AuditDialog },
  mixins: [grid],
  data() {
    const fromDate = moment().format('YYYY-MM-DD 00:00:00');
    const endDate = moment().format('YYYY-MM-DD 23:59:59');
    return {
      tableData: {
        list: [],
      },
      auditStep: 0,
      rowData: {},
      auditDialogVisible: false,
      filters: {
        page: 1,
        size: 20,
        startDate: fromDate,
        endDate,
        changeType: undefined,
        userType: -1,
        subType: '2,1',
      },
      filterDateType: false,
      dataPermissionObj: {
        1: ['redPacket-firstAudit', 'redPacket-secondAudit'],
        2: ['bonusActivity-firstAudit', 'bonusActivity-secondAudit'],
        3: ['manualRecharge-firstAudit', 'manualRecharge-secondAudit'],
        4: ['withdrawFailedSendBack-firstAudit', 'withdrawFailedSendBack-secondAudit'],
        5: ['transferAddScore-firstAudit', 'transferAddScore-secondAudit'],
        6: ['gameAddScore-ballBetSport-firstAudit', 'gameAddScore-ballBetSport-secondAudit'],
        7: ['gameAddScore-LbLottery-firstAudit', 'gameAddScore-LbLottery-secondAudit'],
        8: ['addScoreBonus-firstAudit', 'addScoreBonus-secondAudit'],
        9: [['addMoneyCommissionAdjust-firstAudit', 'addMoneyCommissionAdjust-secondAudit'], ['minusMoneyCommissionAdjust-firstAudit', 'minusMoneyCommissionAdjust-secondAudit']],
        10: ['systemBrokerage-firstAudit', 'systemBrokerage-secondAudit'],
        11: ['mistakeAddScoreSendBack-firstAudit', 'mistakeAddScoreSendBack-secondAudit'],
        25: ['virtualLines-firstAudit', 'virtualLines-secondAudit'],
      },
      menuId: undefined,
    };
  },
  filters: {
    toSwitchStr(type) {
      let str = ';';
      // eslint-disable-next-line default-case
      switch (type) {
        case 1009:
          str = '加币-计入红利';
          break;
        case 1018:
          str = '加币-不计入红利';
          break;
        case 1011:
          str = '减币';
          break;
        case 1:
          str = '红包';
          break;
        case 2:
          str = '活动红利';
          break;
        case 3:
          str = '人工充值';
          break;
        case 4:
          str = '提现失败退回';
          break;
        case 5:
          str = '转账补分';
          break;
        case 6:
          str = '游戏补分-贝博体育';
          break;
        case 7:
          str = '游戏补分-LB彩票';
          break;
        case 8:
          str = '上分返利';
          break;
        case 9:
          str = '佣金调整';
          break;
        case 10:
          str = '系统扣回';
          break;
        case 11:
          str = '错误上分扣回';
          break;
        case 25:
          str = '虚拟额度';
          break;
        default:
          str = '-';
      }
      return str;
    },
  },
  methods: {
    toAudit(row, num) {
      const keyWord = row.subType === 9
        ? (row.changeType === 1018 ? this.dataPermissionObj[row.subType][0][num] : this.dataPermissionObj[row.subType][1][num])
        : this.dataPermissionObj[row.subType][num];
      const menuId = dataPermission.DATA_PERMISSION[keyWord];
      this.showAuditDialog(row, num + 1, menuId);
    },
    initChangeType() {
      if (this.dataRoleCheck('addMoney-addToBonus')) {
        this.filters.changeType = 1009;
      } else if (!this.dataRoleCheck('addMoney-addToBonus') && this.dataRoleCheck('addMoney-noAddToBonus')) {
        this.filters.changeType = 1018;
      } else if (!this.dataRoleCheck('addMoney-addToBonus') && !this.dataRoleCheck('addMoney-noAddToBonus') && this.dataRoleCheck('minusMoney')) {
        this.filters.changeType = 1011;
      } else if (!this.dataRoleCheck('addMoney-addToBonus') && !this.dataRoleCheck('addMoney-noAddToBonus') && !this.dataRoleCheck('minusMoney')) {
        this.filters.changeType = undefined;
      }
    },
    showAuditDialog(row, step, menuId) {
      this.auditDialogVisible = true;
      this.rowData = row;
      this.auditStep = step;
      this.menuId = menuId;
    },

    submitFilterForm(formInline) {
      const { time } = formInline;
      let startDate; let
        endDate;
      if (!_.isUndefined(time) && _.isArray(time)) {
        startDate = time[0];
        endDate = time[1];

        formInline = { ...formInline, startDate, endDate };
      } else {
        this.filters.startDate = undefined;
        this.filters.endDate = undefined;
      }
      this.filters = { ...this.filters, ...formInline };
      this.gridSearch();
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      sums[0] = '本页汇总';

      let totalAmount1 = 0;
      _.each(data, (item) => {
        if (!isNaN(item.amount)) {
          totalAmount1 = _.add(totalAmount1, item.changeType == -2 ? -item.amount : item.amount).toFixed(2);
        } else {

        }
      });
      sums[5] = totalAmount1;
      let totalAmount2 = 0;
      _.each(data, (item) => {
        if (!isNaN(item.freezeAmount)) {
          totalAmount2 = _.add(totalAmount2, item.freezeAmount).toFixed(2);
        } else {

        }
      });
      sums[6] = totalAmount2;

      return sums;
    },
    exportHandle() {
      const {
        startDate, endDate, time, minAmount, maxAmount, userType, keywords, creator, firstApprover, secondApprover, status, changeType, subType,
      } = this.filters;
      const ajaxData = {
        startDate, endDate, time, minAmount, maxAmount, userType, keywords, creator, firstApprover, secondApprover, status, changeType, subType,
      };
      const filename = '资金调整审核明细报表.csv';
      const header = ['资金调整单号', '账户类型', '账户名', '调整类型', '细分类型', '调整金额', '需求流水金额', '申请人', '申请时间', '一审状态', '一审人', '审核时间', '二审状态', '二审人', '审核时间'];
      const filterField = ['orderId', 'userType', 'username', 'changeTypeName', 'subType', 'amount', 'freezeAmount', 'creator', 'createTime', 'status', 'firstApprover', 'firstTime', 'status', 'secondApprover', 'secondTime'];
      exportAduitLogs(ajaxData).then(([result, data]) => {
        if (result) {
          const exportData = this.responseFormatter(data.list);
          this.export2Excel(header, filterField, exportData, filename);
        } else {
          this.$message({ message: `导出失败,${data.message}`, type: 'warning' });
        }
      });
    },
    responseFormatter(data) {
      data.map((item) => {
        item.createTime = _.toTime(item.createTime);
        item.firstTime = _.toTime(item.firstTime);
        item.secondTime = _.toTime(item.secondTime);
        item.userType = _.toConverter(item.userType, 'ACCOUNT_TYPE');
        item.changeTypeName = _.toConverter(item.changeType, 'ADJUSTMENT_TYPES_DETAIL');
        item.subType = this.$options.filters.toSwitchStr(item.subType);
        item.amount = (item.changeType == -2 ? '-' : '') + _.currency(item.amount);
        item.freezeAmount = _.currency(item.freezeAmount);
        item.balance = _.currency(item.balance);
        item.status = _.toConverter(item.status, 'CHECK_STATUS');
      });

      return data;
    },
  },
  mounted() {
    this.initChangeType();
    // tab页记录访问日志
    this.$store.dispatch(types.SAVE_OPERATION_LOG, { content: _.getContent(this.$route, '调整审核', true) });

    this.bindGet(getAdjustmentList, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.getAll();
  },
};
</script>

<style scoped>

</style>
